package com.yunfei.common.auto.createClass;


import com.yunfei.common.auto.GeneratorBase;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;

public class GenInterCtrl  extends GeneratorBase {
	/*
	 * 构造函数
	 */
	public GenInterCtrl(){
    	//创建连接
    	Connection con;
		//查要生成实体类的表
    	String sql = "select * from " + tablename;
    	PreparedStatement pStemt = null;
    	try {
    		try {
				Class.forName(DRIVER);
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			}
    		con = DriverManager.getConnection(URL,NAME,PASS);
			pStemt = con.prepareStatement(sql);
			ResultSetMetaData rsmd = pStemt.getMetaData();
			int size = rsmd.getColumnCount();	//统计列
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < size; i++) {
				colnames[i] = rsmd.getColumnName(i + 1);
				colTypes[i] = rsmd.getColumnTypeName(i + 1);
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}
			String content = parse(colnames,colTypes,colSizes);
			try {
				File directory = new File("");
				String path=this.getClass().getResource("").getPath();
				System.out.println(path);
				System.out.println("src/?/"+path.substring(path.lastIndexOf("/com/")) );
//				String outputPath = directory.getAbsolutePath()+ "/src/"+path.substring(path.lastIndexOf("/com/", path.length()), path.length()) + initcap(tablename) + ".java";
				String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+ CONTROLLER_PATH.replace(".", "/")+"/"+initcap(tablename)+"/"+initcap(tablename)+"Controller" + ".java";
				File file=new File(outputPath);
				file.getParentFile().mkdirs();
				FileWriter fw = new FileWriter(outputPath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
//			try {
//				con.close();
//			} catch (SQLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
    }

	/**
	 * 功能：生成实体类主体代码
	 * @param colnames
	 * @param colTypes
	 * @param colSizes
	 * @return
	 */
	private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
		StringBuffer sb = new StringBuffer();
		String packageTable=replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
		sb.append("package " + CONTROLLER_PATH +"."+initcap(packageTable)+ ";\r\n");
		//tablename=replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
		importPackage(sb,initcap(tablename));
		//注释部分
		sb.append("   /**\r\n");
		sb.append("    *@tablename "+tablename+"\r\n");
		sb.append("    *@author "+this.authorName+"\r\n");
		sb.append("    *@createDate "+new Date()+"\r\n");
		sb.append("    */ \r\n");
		tablename=replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
		//实体部分
		sb.append("\t@Controller\r\n");
		sb.append("\t@RequestMapping(\"/"+tablename+"\")\r\n");
		sb.append("\tpublic class " + initcap(tablename)+"Controller extends BaseCtrl"+ "{\r\n");
		sb.append("\t@Autowired @Qualifier(\""+tablename+"Service\")\r\n");
		sb.append("\tprivate "+initcap(tablename)+"Service "+tablename+"Service;\r\n");
		init(sb,tablename);
		form(sb,tablename,colnames);
	    save(sb,tablename,colnames);
		delete(sb,tablename,colnames);
		findAllList(sb,tablename);
		findAllListPage(sb,tablename);
		repeat(sb,tablename);
		sb.append("}\r\n");
		
		return sb.toString();
	}
	/**
	 * 导入包
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 * @param sb
	 */
	public static void importPackage(StringBuffer sb,String tablename){
		sb.append("import java.util.List;\r\n");
		sb.append("import java.util.Map;\r\n");
		sb.append("import java.util.ArrayList;\r\n");
		sb.append("import java.util.HashMap;\r\n");
		sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
		sb.append("import org.springframework.beans.factory.annotation.Qualifier;\r\n");
		sb.append("import org.springframework.stereotype.Service;\r\n");

		sb.append("import com.yunfei.modular.frontend.dao.mybatis.MBaseDao;\r\n");
		sb.append("import com.yunfei.core.utils.BaseException;\r\n");
		sb.append("import com.yunfei.core.utils.log.BaseLog;\r\n");
		sb.append("import com.yunfei.core.utils.string.StringUtil;\r\n");
		sb.append("import org.springframework.stereotype.Controller;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
		sb.append("import org.springframework.web.bind.annotation.RequestMethod;\r\n");
		sb.append("import org.springframework.web.bind.annotation.ResponseBody;\r\n");
		sb.append("import com.yunfei.modular.frontend.controller.base.BaseCtrl;\r\n");
		sb.append("import com.yunfei.common.json.list.PageUtil;\r\n");
		sb.append("import com.yunfei.common.json.object.ModelJsonUtil;\r\n");
		sb.append("import org.springframework.web.servlet.ModelAndView;\r\n");
		sb.append("import "+BO_PATH+".*;\r\n");
		sb.append("import "+ENTITY_PATH+".*;\r\n");
		sb.append("import "+Interface_PATH+".*;\r\n");
		sb.append("import "+InterfaceImpl_PATH+".*;\r\n");

	}
	/**
	 * 页面跳转初始化
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 * @param sb
	 * @param tablename
	 */
	public static void init(StringBuffer sb,String tablename){
		infoMsg(sb,"页面跳转初始化");
		//sb.append("\t@Autowired @Qualifier(\""+tablename+"\")\r\n");
		//sb.append("\rprivate I"+initcap(tablename)+" "+tablename+";\r\n");
		sb.append("\t@RequestMapping(value=\""+GeneratorBase.pageOutPathPreIndex+"\",method =  RequestMethod.GET)\r\n");
		sb.append("\tpublic ModelAndView forInit(){\t\n");
		sb.append("\t\tModelAndView mv=new ModelAndView(\"/"+GeneratorBase.ModelViewPath+"\");\r\n");
		sb.append("\t\treturn mv;\r\n");
		sb.append("\t\t}\r\n");
	}
	public static void form(StringBuffer sb,String tablename,String[] colnames){
		infoMsg(sb,"新增或者删除页面初始化");
		sb.append("\t@RequestMapping(value = \"/form.shtml\",produces = \"text/html;charset=UTF-8\",method =  RequestMethod.POST)\r\n");
        sb.append("\t@ResponseBody\r\n");
		String pk=colnames[0];//主键列
		String property=replaceUnderlineAndfirstToUpper(pk.toLowerCase(),"_","");//将数据库列转小写，去掉下划线并首字母大写
		sb.append("\tpublic Object  form(String "+property+"){\r\n");
		sb.append("\t\tObject jsonStr=\"\";\r\n");

		sb.append("\t\tif(!StringUtil.isNullOrEmpty("+property+")){\r\n");
		sb.append("\t\t\t"+initcap(tablename)+"Bo bo="+tablename+"Service.findById("+property+");\r\n");
		sb.append("\t\t\tjsonStr = ModelJsonUtil.getJsonBo(bo);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\treturn jsonStr;\r\n");
	    sb.append("\t}\r\n");
	    
	}
	public static void save(StringBuffer sb,String tablename,String [] colnames){
		infoMsg(sb,"保存或者更新信息");
		sb.append("\t@RequestMapping(value=\"/save.shtml\",method =  RequestMethod.POST)\r\n");
        sb.append("\t@ResponseBody\r\n");
		sb.append("\tpublic Map<String,Object>  save("+initcap(tablename)+"Bo bo){\r\n");
		sb.append("\t\tMap<String,Object> map=new HashMap<String, Object>();\r\n");
		sb.append("\t\tboolean flag=false;\r\n");
		sb.append("\t\tString id=\"\";\r\n");
		sb.append("\t\tString backInfo = null;\r\n");
		sb.append("\t\ttry{\r\n");
		//sb.append("\t\tbackInfo = "+tablename+".update(bo);\r\n");
        String pk=colnames[0];//主键列
        String property=replaceUnderlineAndfirstToUpper(pk.toLowerCase(),"_","");//将数据库列转小写，去掉下划线并首字母大写
		sb.append("\t\t\tif(!StringUtil.isNullOrEmpty(bo)&&!StringUtil.isNullOrEmpty(bo.get"+initcap(property)+"())){\r\n");
		sb.append("\t\t\t\t"+tablename+"Service.update(bo);\r\n");
		sb.append("\t\t\t\tid=bo.get"+initcap(property)+"()+\"\";\r\n");
		sb.append("\t\t\t}else{\r\n");
		sb.append("\t\t\t\tid="+tablename+"Service.add(bo);\r\n");
		sb.append("\t\t\t}\r\n");
		sb.append("\t\t\tflag=true;\r\n");
		sb.append("\t\t}catch (Exception e) {\r\n");
		sb.append("\t\t\t\tBaseLog.e(this.getClass(), \"修改成功\", e);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\tmap.put(\"errorNo\",0);\r\n");
		sb.append("\t\tmap.put(\"message\",\"\");\r\n");
		sb.append("\t\tmap.put(\"id\",id);\r\n");
		sb.append("\t\treturn map;\r\n");
	    sb.append("\t}\r\n");
	}
	public static void delete(StringBuffer sb,String tablename,String [] colnames){
		infoMsg(sb,"删除");
		sb.append("\t@RequestMapping(value=\"/delete.shtml\",method =  RequestMethod.POST)\r\n");
        sb.append("\t@ResponseBody\r\n");
        String pk=colnames[0];//主键列
        String property=replaceUnderlineAndfirstToUpper(pk.toLowerCase(),"_","");//将数据库列转小写，去掉下划线并首字母大写
	    sb.append("\tpublic Map<String,Object>  delete(String "+property+"){\r\n");
		sb.append("\t\tMap<String,Object> map=new HashMap<String, Object>();\r\n");
		sb.append("\t\tString backInfo = null;\r\n");
		sb.append("\t\ttry{\r\n");
		sb.append("\t\t\tbackInfo = "+tablename+"Service.delete("+property+");\r\n");
		sb.append("\t\t}catch (Exception e) {\r\n");
		sb.append("\t\t\tmap.put(\"message\",0);\r\n");
		sb.append("\t\t\tBaseLog.e(this.getClass(), \"新增成功\", e);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t\tmap.put(\"errorNo\",0);\r\n");
		sb.append("\t\tmap.put(\"message\",\"\");\r\n");
		sb.append("\t\treturn map;\r\n");
	    sb.append("\t}\r\n");
	}

	/**
	 * 查询所有信息
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 * @param sb
	 * @param tablename
	 */
	public static void findAllList(StringBuffer sb,String tablename){
		infoMsg(sb,"查询所有信息");
		sb.append("\t@RequestMapping(value=\"/findAllList.shtml\",method =  RequestMethod.POST)\r\n");
	    sb.append("\t@ResponseBody\r\n");
		sb.append("\tpublic Map<String,Object> findAllList("+initcap(tablename)+"Bo bo){\r\n");
		sb.append("\tMap<String,Object> jsonMap = new HashMap<String, Object>();\r\n");
		sb.append("\ttry {\r\n");
		sb.append("\t\tint total=0;\r\n");
		sb.append("\t\ttotal="+tablename+"Service.count(bo);\r\n");
		sb.append("\t\tList<"+initcap(tablename)+"Bo> list = "+tablename+"Service.findAllList(bo);\r\n");
		sb.append("\t\tjsonMap.put(\"Rows\", list);\r\n");
		sb.append("\t\tjsonMap.put(\"Total\", total);\r\n");
		sb.append("\t} catch (Exception e) {\r\n");
		sb.append("\t\tBaseLog.e(this.getClass(), \"queryArticleList:查询有误\", e);\r\n");
		sb.append("\t}\r\n");
		sb.append("\t\treturn jsonMap;\r\n");
		sb.append("\t}\r\n");
	}

	/**
	 * 查询所有信息
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 * @param sb
	 * @param tablename
	 */
	public static void findAllListPage(StringBuffer sb,String tablename){
		infoMsg(sb,"查询所有信息");
		sb.append("\t@RequestMapping(value = \"/findAllListPage.shtml\",produces = \"text/html;charset=UTF-8\",method =  RequestMethod.POST)\r\n");
		sb.append("\t@ResponseBody\r\n");
		sb.append("\tpublic Object findAllList("+initcap(tablename)+"Bo bo,String field, String order,String pageNum,String pageSize){\r\n");
		sb.append("\tObject jsonStr=\"\";\r\n");
		sb.append("\ttry {\r\n");
		sb.append("\t\t\t/************* 分页处理 ************/\r\n");
		sb.append("\t\tint skip;\r\n");
		sb.append("\t\tint max;\r\n");
		sb.append("\t\tif (StringUtil.isNullOrEmpty(pageNum))\r\n");
		sb.append("\t\tpageNum = \"0\";\r\n");
		sb.append("\t\tif (StringUtil.isNullOrEmpty(pageSize))\r\n");
		sb.append("\t\tpageSize = \"20\";\r\n");
		sb.append("\t\tskip = Integer.parseInt(pageNum);\r\n");
		sb.append("\t\tmax = Integer.parseInt(pageSize);\r\n");
		sb.append("\t\t/************  分页处理结束 ***********/\r\n");
		sb.append("\t\tint total=0;\r\n");
		sb.append("\t\tbo.setCurNo(skip);\r\n" +
				"\t\tbo.setCurSize(max);\r\n");
		sb.append("\t\tbo.setField("+initcap(tablename)+"Bo.changeFieldColumn(field));\n" +
				"\t\tbo.setOrder(order);\r\n");
		sb.append("\t\ttotal="+tablename+"Service.count(bo);\r\n");
		sb.append("\t\tList<"+initcap(tablename)+"Bo> list = "+tablename+"Service.findAllList(bo, skip, max);\r\n");
		sb.append("\t\tjsonStr = PageUtil.getPageJson(pageNum, pageSize, max, total, list);\r\n");
		sb.append("\t} catch (Exception e) {\r\n");
		sb.append("\t\tBaseLog.e(this.getClass(), \"queryArticleList:查询有误\", e);\r\n");
		sb.append("\t}\r\n");
		sb.append("\t\treturn jsonStr;\r\n");
		sb.append("\t}\r\n");
	}
	/**
	 * 查询是否重复
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 * @param sb
	 * @param tablename
	 */
	public static void repeat(StringBuffer sb,String tablename){
		infoMsg(sb,"查询是否重复");
		sb.append("\t@RequestMapping(value=\"/repeat.shtml\",method =  RequestMethod.POST)\r\n");
	    sb.append("\t@ResponseBody\r\n");
		sb.append("\tpublic Map<String,Object> repeat("+initcap(tablename)+"Bo bo){\r\n");
		sb.append("\tMap<String,Object> jsonMap = new HashMap<String, Object>();\r\n");
		sb.append("\ttry {\r\n");
		sb.append("\t\tint total=0;\r\n");
		sb.append("\t\ttotal="+tablename+"Service.count(bo);\r\n");
		sb.append("\tif(total>0){\r\n");
		sb.append("\t\tjsonMap.put(\"result\",true);\r\n");
		sb.append("\t}else{\r\n");
		sb.append("\t\tjsonMap.put(\"result\",false);\r\n");
		sb.append("\t\t\r}\r\n");
		sb.append("\t} catch (Exception e) {\r\n");
		sb.append("\t\tBaseLog.e(this.getClass(), \"queryArticleList:查询有误\", e);\r\n");
		sb.append("\t}\r\n");
		sb.append("\t\treturn jsonMap;\r\n");
		sb.append("\t}\r\n");
	}
	/**
	 * 自动生成注释
	 *@title
	 *@date 2014-10-17
	 *@author ZhengYunfei
	 */
	public static void infoMsg(StringBuffer sb,String msg){
		sb.append("\t/**\r\n");
		sb.append("\t*"+msg+"\r\n");
		sb.append("\t*@author zhengYunFei\r\n");
		sb.append("\t*@date "+new Date()+"\r\n");
		sb.append("\t*/\r\n");
	}
	/** 
	* 首字母大写 
	*  
	* @param srcStr 
	* @return 
	*/  
	public static String firstCharacterToUpper(String srcStr) {  
	   return srcStr.substring(0, 1).toUpperCase() + srcStr.substring(1);  
	}  
	/** 
	* 替换字符串并让它的下一个字母为大写 
	* @param srcStr 
	* @param org 
	* @param ob 
	* @return 
	*/  
	public static String replaceUnderlineAndfirstToUpper(String srcStr,String org,String ob)  
	{  
	   String newString = "";  
	   int first=0;  
	   while(srcStr.indexOf(org)!=-1)  
	   {  
	    first=srcStr.indexOf(org);  
	    if(first!=srcStr.length())  
	    {  
	     newString=newString+srcStr.substring(0,first)+ob;  
	     srcStr=srcStr.substring(first+org.length());
	     srcStr=firstCharacterToUpper(srcStr);  
	    }  
	   }  
	   newString=newString+srcStr;  
	   return newString;  
	}  
	

	/**
	 * 功能：将输入字符串的首字母改成大写
	 * @param str
	 * @return
	 */
	private static String initcap(String str) {
		
		char[] ch = str.toCharArray();
		if(ch[0] >= 'a' && ch[0] <= 'z'){
			ch[0] = (char)(ch[0] - 32);
		}
		
		return new String(ch);
	}

	/**
	 * 出口
	 * TODO
	 * @param args
	 */
	public static void main(String[] args) {
		
		new GenInterCtrl();
		
	}

}